package com.yangrd.helper.crudhelper.core.crud.page.impl;

import com.alibaba.fastjson.JSON;
import com.yangrd.helper.crudhelper.core.crud.page.TranslateService;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description: BingTranslateService
 *
 * @author: yangrd
 * @date: 2020/9/15
 * @version: 1.0
 */
public class BingTranslateService implements TranslateService {

    private final RestTemplate client = new RestTemplate();

    @Override
    public String translateCN(String english) {
        Map<String, String> body = new HashMap<>(6);
        body.put("fromLang", "auto-detect");
        body.put("text", english);
        body.put("to", "zh-Hans");
        return JSON.parseArray(post(body)).getJSONObject(0).getJSONArray("translations").getJSONObject(0).getString("text");
    }


    /**
     * @param body
     * @return [
     * {
     * "detectedLanguage": {
     * "language": "en",
     * "score": 1.0
     * },
     * "translations": [
     * {
     * "text": "你好",
     * "transliteration": {
     * "text": "nǐ hǎo",
     * "script": "Latn"
     * },
     * "to": "zh-Hans",
     * "sentLen": {
     * "srcSentLen": [
     * 5
     * ],
     * "transSentLen": [
     * 2
     * ]
     * }
     * }
     * ]
     * }
     * ]
     */
    private String post(Map<String, String> body) {
        String url = "https://cn.bing.com/ttranslatev3?isVertical=1&&IG=8FEF307A6408481F8AB02F289074B47C&IID=translator.5028.6";
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, String> form = new LinkedMultiValueMap<>(body.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> Arrays.asList(e.getValue()))));
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(form, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
        //  输出结果
        return response.getBody();
    }
}
